//
//  YDChooseCarController.m
//  YDTestDrive
//
//  Created by ios on 2017/2/15.
//  Copyright © 2017年 ios. All rights reserved.
//

#import "YDChooseCarController.h"

#import "YDCarBrandCell.h"
#import "YDCarTypeCell.h"

#import "YDCarBrandModel.h"
#import "YDCarTypeModel.h"
#import "YDCarSeriesModel.h"

#import "AFNetworking.h"


#define kCarTypeTableViewWidth 270.0f

@interface YDChooseCarController () <UITableViewDataSource,UITableViewDelegate,YDCarBrandCellDelegete>
{
    NSString *selectBrandID;  //选中的品牌ID
    NSString *selectCarID;    //选中的车系ID
    NSInteger PYCount;
}
@property (nonatomic, strong) UITableView *brandTableView;
@property (nonatomic, strong) UITableView *carTypeTableView;
@property (nonatomic, strong) UIButton *coverButton;

@property (nonatomic, strong) NSMutableArray *brandArray;
@property (nonatomic, strong) NSMutableArray *carTypeArray;

@property (nonatomic, strong) NSMutableArray *indexArray; //索引数组
@property (nonatomic, strong) UILabel *indexView; //索引view



@end

@implementation YDChooseCarController

- (instancetype)init
{
    if (self = [super init]) {
        _brandArray = [NSMutableArray array];
        _carTypeArray = [NSMutableArray array];
        _indexArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"选择车型";
    
    [self crateView];
    
    [self loadDataFormNetwork];
    
}


#pragma mark - UI
- (void)crateView
{
    _brandTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64.0f) style:UITableViewStyleGrouped];
    _brandTableView.backgroundColor = kViewControllerBackgroundColor;
    _brandTableView.delegate = self;
    _brandTableView.dataSource = self;
    [_brandTableView registerClass:[YDCarBrandCell class] forCellReuseIdentifier:@"YDCarBrandCell"];
    _brandTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_brandTableView];
    
    _coverButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _coverButton.backgroundColor = [UIColor blackColor];
    _coverButton.alpha = 0.4f;
    _coverButton.hidden = YES;
    _coverButton.frame = CGRectMake(0, 0, kScreenWidth, _brandTableView.height);
    [_coverButton addTarget:self action:@selector(coverClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_coverButton];
    
    _carTypeTableView = [[UITableView alloc] initWithFrame:CGRectMake(kScreenWidth, 0, kCarTypeTableViewWidth, _coverButton.height) style:UITableViewStylePlain];
    _carTypeTableView.delegate = self;
    _carTypeTableView.dataSource = self;
    [_carTypeTableView registerNib(@"YDCarTypeCell")];
    _carTypeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_carTypeTableView];
}

#pragma mark 点击遮盖
- (void)coverClick
{
    [self closeChooseCarTypeView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _brandTableView) {
        return self.brandArray.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _brandTableView)
    {
        NSArray *sectionBrandArray = [self.brandArray objectAtIndex:section];
        return sectionBrandArray.count;
    }
    else
    {
        return self.carTypeArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _brandTableView) {
        NSArray *sectionArray = [self.brandArray objectAtIndex:indexPath.section];
        YDCarBrandModel *brandModel = [sectionArray objectAtIndex:indexPath.row];
        YDCarBrandCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YDCarBrandCell"];
        cell.carBrandModel = brandModel;
        cell.delegete = self;
        return cell;
    } else {
        YDCarTypeModel *model = [self.carTypeArray objectAtIndex:indexPath.row];
        YDCarTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YDCarTypeCell"];
        cell.carTypeModel = model;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == _carTypeTableView) {
        
        YDCarTypeModel *model = [self.carTypeArray objectAtIndex:indexPath.row];
        
        if (self.ChooseCarBlock) {
            self.ChooseCarBlock(selectBrandID, selectCarID, model.carTypeId, model.cartypeName);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _brandTableView) {
        NSArray *sectionArray = [self.brandArray objectAtIndex:indexPath.section];
        YDCarBrandModel *brandModel = [sectionArray objectAtIndex:indexPath.row];
        return brandModel.cellHeight;
    } else {
        return 55.0f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

#pragma mark 点击车系回调
- (void)carButtonClickWithCarBrandModel:(YDCarBrandModel *)brandModel carSeriesModel:(YDCarSeriesModel *)carSeriesModel
{
    selectBrandID = brandModel.brandId;
    selectCarID = carSeriesModel.modelId;
    
    [self openChooseCarTypeView];
    
    [self getCarInfoFormNetworkWithParameters:@{@"carsId" : carSeriesModel.modelId}];
}


/**
 打开选择车型界面
 */
- (void)openChooseCarTypeView
{
    _coverButton.hidden = NO;
    _coverButton.alpha = 0;
    
    [UIView animateWithDuration:0.25f animations:^{
       
        _coverButton.alpha = 0.4f;
        _carTypeTableView.frame = CGRectMake(kScreenWidth - kCarTypeTableViewWidth, 0, kCarTypeTableViewWidth, _coverButton.height);
        
    }];
}
/**
 关闭选择车型界面
 */
- (void)closeChooseCarTypeView
{
    [UIView animateWithDuration:0.25f animations:^{
        
        _coverButton.alpha = 0;
        _carTypeTableView.frame = CGRectMake(kScreenWidth, 0, kCarTypeTableViewWidth, _coverButton.height);
        
    } completion:^(BOOL finished) {
        _coverButton.hidden = YES;
    }];
}

#pragma mark - 网络部分
#pragma mark 获取车型
- (void)getCarInfoFormNetworkWithParameters:(NSDictionary *)parameters
{

    [_carTypeArray removeAllObjects];
    
    NSString *URL = [NSString stringWithFormat:@"%@sid=%@", kChooseBrands, getNSUser(kAPP_SID)];
    
    [YDDataService POST:parameters url:URL block:^(id result) {
        
        if ([[result valueForKey:@"code"] isEqualToString:@"S_OK"]) {
            NSArray *carsArray = [result valueForKey:@"var"];
            
            for (NSDictionary *dic in carsArray) {
                YDCarTypeModel *model = [YDCarTypeModel instanceWithDict:dic];
                [_carTypeArray addObject:model];
                [_carTypeTableView reloadData];
            }
            
        }
        
    } failBlock:^(id error) {
        
    }];
}

#pragma mark 获取品牌车系
- (void)loadDataFormNetwork
{
    
    NSString *URL = [NSString stringWithFormat:@"%@sid=%@", kChooseBrands, getNSUser(kAPP_SID)];
    
    [YDDataService POST:@{} url:URL block:^(id result) {
        
        if ([[result valueForKey:@"code"] isEqualToString:@"S_OK"]) {
            NSArray *brandArray = [result valueForKey:@"var"];
            
            NSMutableArray *tempArray = [NSMutableArray array];
            
            for (NSDictionary *dic in brandArray) {
                YDCarBrandModel *brandModel = [YDCarBrandModel carBrandModelWithDictionary:dic];
                [tempArray addObject:brandModel];
            }
            
            self.brandArray = [self sortObjectsAccordingToInitialWith:tempArray];
            
            [self getNamePinYinArray];
            
            [self createIndexView];
            
            [self.brandTableView reloadData];
        }
        
    } failBlock:^(id error) {
        
    }];
}

#pragma mark - ===================索引===================
#pragma mark 创建索引条
- (void)createIndexView
{
    PYCount = self.indexArray.count;
    
    //初始化右边索引条
    _indexView=[[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth-15,(kScreenHeight-PYCount * 14.6f - 64.0f)/2,13,PYCount * 14.6f)];
    _indexView.numberOfLines=0;
    _indexView.font=[UIFont systemFontOfSize:12];
    _indexView.backgroundColor=[UIColor clearColor];
    _indexView.textAlignment=NSTextAlignmentCenter;
    _indexView.userInteractionEnabled=YES;
    _indexView.layer.cornerRadius=5;
    _indexView.layer.masksToBounds=YES;
    _indexView.alpha=0.7;
    [self.view addSubview:_indexView];
    [self.view insertSubview:_indexView atIndex:1];
    
    //初始化索引条内容
    for (int i=0; i<PYCount; i++)
    {
        NSString *str= self.indexArray[i];
        _indexView.text = i==0 ? str : [NSString stringWithFormat:@"%@\n%@",_indexView.text,str];
    }
}

//点击开始
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self myTouch:touches];
}


//点击进行中
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self myTouch:touches];
}

//点击结束
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}

//点击会掉的方法
-(void)myTouch:(NSSet *)touches
{
    //获取点击的区域
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:_indexView];
    
    int index=(int)((point.y/(PYCount * 14.6f))*PYCount);
    if (index>PYCount - 1||index<0)return;
    
    //跳到tableview指定的区
    NSIndexPath *indpath=[NSIndexPath indexPathForRow:0 inSection:index];
    [self.brandTableView  scrollToRowAtIndexPath:indpath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}


#pragma mark - ===================排序分组===================
// 按首字母分组排序数组
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
    
    // 初始化UILocalizedIndexedCollation
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    //得出collation索引的数量，这里是27个（26个字母和1个#）
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    //初始化一个数组newSectionsArray用来存放最终的数据，我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    
    //初始化27个空数组加入newSectionsArray
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    
    //将每个名字分到某个section下
    for (YDCarBrandModel *carBrandModel in arr) {
        //获取name属性的值所在的位置，比如"林丹"，首字母是L，在A~Z中排第11（第一位是0），sectionNumber就为11
        NSInteger sectionNumber = [collation sectionForObject:carBrandModel collationStringSelector:@selector(brandName)];
        //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
        NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
        [sectionNames addObject:carBrandModel];
    }
    
    //对每个section中的数组按照name属性排序
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *personArrayForSection = newSectionsArray[index];
        NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(brandName)];
        newSectionsArray[index] = sortedPersonArrayForSection;
    }
    
    //删除空的数组
    NSMutableArray *finalArr = [NSMutableArray new];
    for (NSInteger index = 0; index < sectionTitlesCount; index++) {
        if (((NSMutableArray *)(newSectionsArray[index])).count != 0) {
            [finalArr addObject:newSectionsArray[index]];
        }
    }
    
    return finalArr;
}

- (void)getNamePinYinArray
{
    for (int i = 0; i < self.brandArray.count; i++) {
        YDCarBrandModel *carBrandModel = [self.brandArray[i] lastObject];
        NSString *pinYin = [self firstCharactor:carBrandModel.brandName];
        [self.indexArray addObject:pinYin];
    }
}

//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
- (NSString *)firstCharactor:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
